package cn.juque.jdfsystem.listener;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ClassUtil;
import cn.juque.common.utils.FastJsonUtil;
import cn.juque.jdfsystem.entity.FileInfo;
import cn.juque.jdfsystem.threads.DelFileThreadPool;
import cn.juque.lucenecandy.core.base.BaseMessageEntity;
import cn.juque.lucenecandy.core.base.IdsQueryWrapperBuilder;
import cn.juque.lucenecandy.core.datasync.listener.IMsgWriteListener;
import cn.juque.lucenecandy.core.enums.DocSyncTypeEnum;
import cn.juque.lucenecandy.helper.IndexHelper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author juque
 * @version 1.0.0
 * <ul>
 *     <li>FileDelWriteListener</li>
 * </ul>
 * @date 2024-01-05
 **/
@Service("fileDelWriteListener")
public class FileDelWriteListener implements IMsgWriteListener {

    @Resource
    private DelFileThreadPool delFileThreadPool;

    @Resource
    private IndexHelper indexHelper;

    @Override
    public Boolean before(BaseMessageEntity messageEntity) {
        DocSyncTypeEnum syncTypeEnum = DocSyncTypeEnum.valueOf(messageEntity.getSyncType());
        if (ClassUtil.equals(FileInfo.class, messageEntity.getClassName(), false)
                && DocSyncTypeEnum.DEL.equals(syncTypeEnum)) {
            List<String> idList = FastJsonUtil.parseArray(messageEntity.getBody(), String.class);
            if (CollUtil.isNotEmpty(idList)) {
                IdsQueryWrapperBuilder<FileInfo> idsQueryWrapperBuilder = new IdsQueryWrapperBuilder<>(FileInfo.class, idList);
                List<FileInfo> infoList = this.indexHelper.searchByIds(idsQueryWrapperBuilder.build());
                infoList.forEach(f -> this.delFileThreadPool.execute(f));
            }
        }
        return true;
    }

    @Override
    public void after(BaseMessageEntity messageEntity) {
        // do nothing
    }
}
